<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>每日记忆</title>
    <link rel="stylesheet" href="css/style.css">
    <!-- Quill.js 富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
</head>
<body>
    <div class="daily-page">
        <div class="header">
            <button class="back-btn" onclick="goBack()">返回</button>
            <div class="group-info">
                <span id="groupName">第1组</span>
                <span class="day-info" id="currentDay">第1天</span>
            </div>
            <div class="header-actions">
                <button class="batch-edit-btn" onclick="openBatchEdit()">批量编辑记忆内容</button>
                <button class="more-btn" onclick="toggleMore()">更多
                    <div class="more-menu" id="moreMenu" style="display: none;">
                        <div class="menu-item danger" onclick="deleteCurrentGroupMemories()">删除当前记忆</div>
                        <div class="menu-item warning" onclick="resetGroupTimer()">重新开始记忆计时</div>
                    </div>
                </button>
            </div>
        </div>

        <div class="input-section">
            <div class="input-group">
                <input type="text" id="hintInput" placeholder="输入记忆提示" class="memory-input">
                <div class="rich-text-container">
                    <div id="contentEditor" class="rich-text-editor"></div>
                </div>
                <button class="add-btn" onclick="addMemory()">添加</button>
            </div>
        </div>

        <div class="memories-section">
            <div class="section-title">今日记忆内容</div>
            <div class="memories-list" id="memoriesList">
                <!-- 记忆内容将在这里动态生成 -->
            </div>
        </div>

    </div>

    <script src="js/utils.js"></script>
    <script src="js/db.js"></script>
    <script src="js/app.js"></script>
    <script>
        let currentGroupId = null;
        let currentDay = 1;
        let currentGroup = null;
        let isDeleteMode = false; // 删除模式状态
        let contentEditor = null; // 富文本编辑器实例

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async function() {
            await initDatabase();
            
            // 从URL参数获取组ID
            const urlParams = new URLSearchParams(window.location.search);
            currentGroupId = parseInt(urlParams.get('groupId'));
            
            if (!currentGroupId) {
                alert('无效的组ID');
                goBack();
                return;
            }

            // 加载组信息
            currentGroup = await db.getGroup(currentGroupId);
            if (!currentGroup) {
                alert('组不存在');
                goBack();
                return;
            }

            document.getElementById('groupName').textContent = currentGroup.name;
            
            // 计算当前天数（基于记忆开始时间和今天）
            currentDay = calculateCurrentDay(currentGroup.memoryStartTime || currentGroup.createTime);
            document.getElementById('currentDay').textContent = `第${currentDay}天`;
            
            // 调试信息
            console.log('组创建时间:', currentGroup.createTime);
            console.log('记忆开始时间:', currentGroup.memoryStartTime);
            console.log('当前天数:', currentDay);
            
            // 初始化富文本编辑器
            initRichTextEditor();
            
            loadTodayMemories();
        });

        // 初始化富文本编辑器
        function initRichTextEditor() {
            const toolbarOptions = [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'indent': '-1'}, { 'indent': '+1' }],
                ['link', 'image'],
                ['clean']
            ];

            contentEditor = new Quill('#contentEditor', {
                theme: 'snow',
                placeholder: '输入你要记忆的完整内容...',
                modules: {
                    toolbar: toolbarOptions
                }
            });
        }

        // 计算当前天数
        function calculateCurrentDay(createTime) {
            const createDate = new Date(createTime);
            const today = new Date();
            
            // 将时间设置为当天的开始时间（00:00:00）进行比较
            createDate.setHours(0, 0, 0, 0);
            today.setHours(0, 0, 0, 0);
            
            const diffTime = today - createDate;
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
            
            // 确保天数至少为1，最多为100
            return Math.max(1, Math.min(diffDays, 100));
        }

        // 格式化时间显示
        function formatTime(createTime) {
            const date = new Date(createTime);
            const now = new Date();
            const diffMs = now - date;
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

            if (diffMinutes < 1) {
                return '刚刚';
            } else if (diffMinutes < 60) {
                return `${diffMinutes}分钟前`;
            } else if (diffHours < 24) {
                return `${diffHours}小时前`;
            } else if (diffDays < 7) {
                return `${diffDays}天前`;
            } else {
                return date.toLocaleDateString('zh-CN', {
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
        }

        // 加载今日记忆内容
        async function loadTodayMemories() {
            // 获取今天需要记忆的内容
            const todayMemories = await getTodayMemories();
            const container = document.getElementById('memoriesList');
            
            if (todayMemories.length === 0) {
                container.innerHTML = '<div class="empty-state">今日暂无记忆内容</div>';
                return;
            }

            // 调试信息
            console.log('加载的记忆内容:', todayMemories);
            todayMemories.forEach(memory => {
                console.log(`记忆 ${memory.id}:`, {
                    hint: memory.hint,
                    content: memory.content,
                    createTime: memory.createTime,
                    formattedTime: formatTime(memory.createTime)
                });
            });

            container.innerHTML = todayMemories.map(memory => `
                <div class="memory-item ${isDeleteMode ? 'delete-mode' : ''}" data-memory-id="${memory.id}" onclick="${isDeleteMode ? '' : `showMemoryContent(${memory.id})`}">
                    <div class="memory-hint">
                        <span class="hint-label">提示</span>
                        <span class="hint-text">${memory.hint || '暂无提示'}</span>
                    </div>
                    <div class="memory-time">
                        ${formatTime(memory.createTime)}
                    </div>
                    ${isDeleteMode ? 
                        `<div class="memory-actions">
                            <button class="delete-confirm-btn" onclick="event.stopPropagation(); confirmDeleteMemory(${memory.id})">确认删除</button>
                        </div>` : 
                        ``
                    }
                </div>
            `).join('');
        }

        // 获取今日需要记忆的内容
        async function getTodayMemories() {
            const memories = await db.getMemoriesByGroup(currentGroupId);
            
            // 筛选今天需要记忆的内容
            return memories.filter(memory => {
                // 新增内容：第N天的内容
                if (memory.day === currentDay) return true;
                
                // 复习内容：根据复习日期数组判断
                const reviewDays = memory.reviewDays || [1, 2, 4, 7, 14, 21, 28, 50];
                return reviewDays.includes(currentDay - memory.day + 1);
            });
        }

        // 添加记忆内容
        async function addMemory() {
            const hint = document.getElementById('hintInput').value.trim();
            const content = contentEditor.root.innerHTML.trim();
            
            if (!hint || !content || content === '<p><br></p>') {
                alert('请输入记忆提示和完整内容');
                return;
            }

            // 检查是否是第一条记忆，如果是则设置记忆开始时间
            const existingMemories = await db.getMemoriesByGroup(currentGroupId);
            if (existingMemories.length === 0) {
                // 这是第一条记忆，设置记忆开始时间
                await db.updateGroup(currentGroupId, {
                    memoryStartTime: new Date().toISOString()
                });
                // 更新当前组信息
                currentGroup.memoryStartTime = new Date().toISOString();
            }

            // 添加新的记忆内容
            await db.addMemory({
                groupId: currentGroupId,
                day: currentDay,
                hint: hint,
                content: content,
                reviewDays: [1, 2, 4, 7, 14, 21, 28, 50]
            });

            // 清空输入框
            document.getElementById('hintInput').value = '';
            contentEditor.setContents([]);
            
            // 重新加载记忆内容
            loadTodayMemories();
        }


        // 进入删除模式
        function deleteCurrentGroupMemories() {
            isDeleteMode = true;
            loadTodayMemories(); // 重新渲染记忆卡片，显示删除按钮
        }

        // 确认删除记忆
        async function confirmDeleteMemory(memoryId) {
            if (confirm('确定要删除这条记忆内容吗？')) {
                await db.deleteMemory(memoryId);
                loadTodayMemories();
            }
        }

        // 显示记忆内容弹框
        async function showMemoryContent(memoryId) {
            try {
                const memory = await db.getMemory(memoryId);
                if (!memory) {
                    alert('记忆内容不存在');
                    return;
                }

                // 创建弹框HTML
                const modal = document.createElement('div');
                modal.className = 'memory-modal';
                modal.innerHTML = `
                    <div class="modal-overlay" onclick="closeMemoryModal()"></div>
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>记忆内容</h3>
                            <button class="close-btn" onclick="closeMemoryModal()">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="memory-content-display rich-text-content">
                                ${memory.content || '暂无内容'}
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="modal-btn" onclick="closeMemoryModal()">关闭</button>
                        </div>
                    </div>
                `;

                document.body.appendChild(modal);
            } catch (error) {
                console.error('显示记忆内容失败:', error);
                alert('显示记忆内容失败，请重试');
            }
        }

        // 关闭记忆内容弹框
        function closeMemoryModal() {
            const modal = document.querySelector('.memory-modal');
            if (modal) {
                modal.remove();
            }
        }

        // 重新开始记忆计时
        async function resetGroupTimer() {
            if (confirm('确定要重新开始记忆计时吗？这将重置当前组的记忆开始时间，但不会删除记忆内容。')) {
                try {
                    // 更新组的记忆开始时间为当前时间
                    await db.updateGroup(currentGroupId, {
                        memoryStartTime: new Date().toISOString()
                    });
                    
                    // 更新当前组信息
                    currentGroup.memoryStartTime = new Date().toISOString();
                    
                    // 重新计算当前天数
                    currentDay = calculateCurrentDay(currentGroup.memoryStartTime);
                    document.getElementById('currentDay').textContent = `第${currentDay}天`;
                    
                    // 重新加载记忆内容
                    loadTodayMemories();
                    
                    alert('记忆计时已重新开始！');
                } catch (error) {
                    console.error('重置计时失败:', error);
                    alert('重置计时失败，请重试');
                }
            }
        }

        // 打开批量编辑
        function openBatchEdit() {
            window.location.href = `batch-edit.html?groupId=${currentGroupId}`;
        }

        // 切换更多菜单
        function toggleMore() {
            const menu = document.getElementById('moreMenu');
            menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
        }

        // 点击空白区域关闭更多菜单
        document.addEventListener('click', function(event) {
            const menu = document.getElementById('moreMenu');
            const moreBtn = document.querySelector('.more-btn');
            
            // 如果点击的不是更多按钮和菜单，则关闭菜单
            if (!moreBtn.contains(event.target) && menu.style.display === 'block') {
                menu.style.display = 'none';
            }
        });

        // 返回上一页
        function goBack() {
            window.location.href = 'groups.html';
        }
    </script>
</body>
</html>
